﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpShare.Storage;
using SharpShare.Diagnostics;
using SharpShare.Storage.Security;

namespace SharpShare.Afp.Protocol.Handlers {
    internal class AfpSetExtAttributeRequestHandler : IAfpRequestHandler {
        public const string CustomMetadataNamePrefix = "com.sharpshare.afp.custom:";

        public byte CommandCode {
            get { return 70; }
        }

        public AfpResultCode Process(IAfpSession session, DsiHeader dsiHeader, AfpStream requestStream, AfpStream responseStream) {
            requestStream.ReadPadding();

            ushort volumeId = requestStream.ReadUInt16();
            uint directoryID = requestStream.ReadUInt32();
            AfpExtendedAttributesBitmap fileBitmap = requestStream.ReadEnum<AfpExtendedAttributesBitmap>();
            long offset = requestStream.ReadInt64();
            IAfpVolume volume;
            IStorageItem item = requestStream.ReadPathAndFind(session, volumeId, directoryID, out volume).DemandExists();

            item.GetEffectiveAccess(session).DemandRight(StorageAccessRight.ModifyMetadata);

            requestStream.ReadPadding();

            string name = requestStream.ReadUTF8String();
            uint dataLength = requestStream.ReadUInt32();
            byte[] attrData = requestStream.ReadBytes(dataLength);

            string useName = (CustomMetadataNamePrefix + name);
            item.AddMetadata(useName, attrData);

            Log.Add(session, EntryType.Debug, "Session '{0}' set extended attribute '{1}' with value of size {2} byte(s).", session, name, attrData.Length);

            return AfpResultCode.FPNoErr;
        }
    }
}
